var urlApi = "http://japenagosc.dyndns.org:1220/wiki/api.php";

var targetArticleName = "Leo Brouwer";
var sourceArticleName = "History of Israel";

// Raw data and Metadata
var $sourceArticleSectionsMetadata;
var sourceArticleContent;

var $targetArticleSectionsMetadata;
var targetArticleContent;

// Sections
var sourceSectionsContent = new Array();
var sourceSectionsLevel = new Array();
var sourceSectionsIndex = new Array();

//Sections
var targetSectionsContent = new Array();
var targetSectionsLevel = new Array();
var targetSectionsIndex = new Array();

// Levels
var sourceLevels = new Array();
var targetLevels = new Array();

// Sections to transclude
var contentOfSectionsToTransclude = new Array(); // Content of the NEW transcluded sections (to save in target article)
var targetIndexOfSectionsToTransclude = new Array(); // Index of target section to add new transcluded section AFTER
var sourceIndexOfSectionsToTransclude = new Array(); // Index of source section to edit and add the <transclusion> tag
var indexesOfNewTransclusions = new Array(); // Indexes of the "new" unregistrered transclusions. These have to be updated in the DB later
var levelOfSourceSections = new Array(); //
var ordenSources = new Array(); // usado para organizar de mayor a menor el orden de ejecución y de registro de las transclusiones segun sIndex

var flagTooltip = false;

$(document).ready(function(){
  // The visuals are loaded
  initLoadingDiv();

  // The articles are loaded in the arrays
  loadArticles();

  $("#previewSectionText").hide();
  $(document).mousemove(showPreviewText);

  $("#divCanvas").css({
	  "position":"absolute",
	  "bottom":(window.screen.availHeight * 0.5 - 250) + "px",
	  "left":(window.screen.availWidth * 0.5 - 300) + "px"
  });

  $("#botonGuardarCambios").css({
	  "width":"200px",
	  "position":"absolute",
	  "bottom":"50px",
	  "left":(window.screen.availWidth * 0.5 - 100 )+"px"
  }).click(saveChanges);
});

function showPreviewText(event){
  $("#previewSectionText").css({
    "position" : "absolute",
    "top" : event.pageY,
    "left" : event.pageX,

    "max-width" : "400px",
    "max-height" : "300px",

    "background-color" : "#FFF",
    "text-align" : "justify",
    "text-color" : "#000",
    "font-size" : "11px",
    "margin" : "10px",
    "padding" : "10px",

    "text-overflow" : "ellipsis",
    "white-space" : "normal",
    "overflow" : "hidden",
    "z-index":"9999"
  });

  if(flagTooltip){
    $("#previewSectionText").show("slow", function(){});
  }
  else{
    $("#previewSectionText").hide("slow", function(){});
  }
}

function loadArticles(){
  // Target Article
  $.ajax({
    url: urlApi,

    data:{
	action:'parse',
	format:'xml',

	page:targetArticleName,
	prop:'sections|wikitext'
    },

    dataType: 'xml',

    success: function(data){
	// The data is parsed into two variables
	$targetArticleSectionsMetadata = $( data );
	targetArticleContent = $( data ).find('wikitext').text();

	// It is initialized
	initArticleContents('TARGET');

	var pjs = Processing.getInstanceById('pSketch');
	pjs.loadTargetArticleSketch(0);
    }
  });

  // Source Article
  $.ajax({
    url: urlApi,

    data:{
	action:'parse',
	format:'xml',

	page:sourceArticleName,
	prop:'sections|wikitext'
    },

    dataType: 'xml',

    success: function(data){
	// The data is parsed into two variables
	$sourceArticleSectionsMetadata = $( data );
	sourceArticleContent = $( data ).find('wikitext').text();

	// It is initialized
	initArticleContents('SOURCE');

	var pjs = Processing.getInstanceById('pSketch');
	pjs.loadSourceArticleSketch(0);
    }
  });
}

function initArticleContents(articleType){
  // articleType = 'SOURCE' or 'TARGET'

  // Local variable
  var localLevels = new Array();
  var $tempArticleSectionsMetadata, tempLevels, tempSectionsLevel, tempSectionsIndex, tempSectionsContent, tempArticleContent;

  if(articleType == 'SOURCE'){
    $tempArticleSectionsMetadata = $sourceArticleSectionsMetadata;
    tempLevels = sourceLevels;

    tempSectionsLevel = sourceSectionsLevel;
    tempSectionsIndex = sourceSectionsIndex;
    tempSectionsContent = sourceSectionsContent;

    tempArticleContent = sourceArticleContent;
  }
  else{
    $tempArticleSectionsMetadata = $targetArticleSectionsMetadata;
    tempLevels = targetLevels;

    tempSectionsLevel = targetSectionsLevel;
    tempSectionsIndex = targetSectionsIndex;
    tempSectionsContent = targetSectionsContent;

    tempArticleContent = targetArticleContent;
  }

  var j=0;
  $tempArticleSectionsMetadata.find( "s" ).each(function(){
    $tempValue = $(this);

    // Loads the values of leveling
    $tempArticleSectionsMetadata.find( "s" ).each(function(){
	$tempValue2 = $(this);

	if( localLevels[ $(this).attr('level') ] != 'x'){ // If not added
	  tempLevels[j] = $tempValue2.attr("level");
	  j++;

	  localLevels[ $(this).attr('level') ] = 'x';
	}
    });
  });

  i=0;
  $.each(tempLevels,function(ij,n){
    // i index n value
    // Get the total elements of level N
    numberOfElements = $tempArticleSectionsMetadata.find("s[level=" + n + "]").size();

    $tempArticleSectionsMetadata.find( "s" ).each(function(){
	$tempValue = $(this);

	// Por cada uno, recorrer el arreglo y agregar los de nro mayor hasta que se llegue al final o al otro elemnto del mismo nivel
	if( $tempValue.attr("level") == n ){
	  // Another instance found... check later if == 0
	  numberOfElements--;

	  // The values we already have
	  tempSectionsLevel[i] = $tempValue.attr('level');
	  tempSectionsIndex[i] = $tempValue.attr('index');

	  // the start section offset
	  sectionOffset = $tempValue.attr('byteoffset');

	  if( numberOfElements == 0 ){
	    // if == 0 then substring the rest of the elements
	    tempSectionsContent[i] = tempArticleContent.substring( sectionOffset );
	  }
	  else{
	    if( numberOfElements > 0 ){
		// if > 0 then substring subset
		desiredLevel = $tempValue.attr("level");

		$tempValue2 = $tempValue.next();
		$tempValue = $tempValue2;

		while( desiredLevel < $tempValue.attr("level") ){
		  $tempValue2 = $tempValue.next();
		  $tempValue = $tempValue2;
		}

		nextOffset = $tempValue.attr("byteoffset");

		tempSectionsContent[i] = tempArticleContent.substring( sectionOffset, nextOffset );
	    }
	  }
	  i++;
	}
    });
  });
}

function previewText(sectionContent){
  if(sectionContent == ''){
    flagTooltip = false;

    // Trigger the event
    $(document).mousemove();
  }
  else{
    if(sectionContent.length > 5000){
	sectionContent = sectionContent.substr(0,5000);
    }

    $("#previewSectionText").html(sectionContent);

    flagTooltip = true;

    // Trigger the event
    $(document).mousemove();
  }
}

function showTooltip(textToShow){
    $("#additionalTooltip").css({

    "background-color" : "#FFF",
    "text-align" : "center",
    "text-color" : "#F00",
    "font-size" : "16px"
  });

  $("#additionalTooltip").html(textToShow);

  if(textToShow == ""){
      $("#additionalTooltip").hide();
  }
  else{
      $("#additionalTooltip").show();
  }
}

function initLoadingDiv(){
  $("#loadingDiv").hide();

  $("#loadingDiv").css({
    "position" : "absolute",
    "bottom" : "5px",
    "right" : "5px"
  });

  $("#loadingDiv").ajaxStart(function(){
    $(this).show();
  });

  $("#loadingDiv").ajaxStop(function(){
    $(this).hide();
  });
}

function registerNewTranscludedSection(targetIndex, sourceIndex, levelSourceTr){
	contentOfSectionsToTransclude.push(""); // {{#transcludeid: articleName|trid}}
	targetIndexOfSectionsToTransclude.push(targetIndex); // API index
	sourceIndexOfSectionsToTransclude.push(sourceIndex); // API index
	indexesOfNewTransclusions.push(getNewTrid());
	levelOfSourceSections.push(levelSourceTr);

	ordenarSources();
}

function ordenarSources (){
	copiaSources = Array(sourceIndexOfSectionsToTransclude.length);
	for(i=0; i<sourceIndexOfSectionsToTransclude.length; i++){
		copiaSources[i] = sourceIndexOfSectionsToTransclude[i];
	}

	ordenSources = new Array(copiaSources.length);
	for(j = 0; j < ordenSources.length; j++){
		ordenSources[j] = j;
	}

	for(k = 0; k < copiaSources.length - 1; k++){
		for (m = k+1; m < copiaSources.length; m++){
			if(copiaSources[m-1] > copiaSources[m]){
				temp = copiaSources[m-1];
				copiaSources[m-1] = copiaSources[m];
				copiaSources[m] = temp;

				temp = ordenSources[m-1];
				ordenSources[m-1] = ordenSources[m];
				ordenSources[m] = temp;
			}
		}
	}
}

function saveChanges(){
  /*
   * Function that saves the changes made to the target article
   * NOTE:
   * - The level of the target article will be fixed, it only registers the transclusion(s) made in the current level
   */

  // Target Article
  $.ajax({
    url: urlApi, // first, the token acquisition

    data:{
	action:'query',
	format:'xml',

	prop:'info',
	intoken:'edit',
	titles:targetArticleName + "|" + sourceArticleName
    },

    dataType: 'xml',

    success: function(data){
	eToken = $( data ).find('page').attr('edittoken');

	$.each(ordenSources, function(index, value) {
		$("#divGuardarCambios").append("<span id='" + indexesOfNewTransclusions[value] + "'>Transclusion from <b>" + sourceArticleName + "</b> to <b>" + targetArticleName + "</b>, section <b>" + sourceIndexOfSectionsToTransclude[value] +  "</b>: </span><br/>");

		eTargetContent = "";
		$.each(targetSectionsIndex, function(eTIndex, eTValue){
			if(eTValue == targetIndexOfSectionsToTransclude[value] ){
				eTargetContent = targetSectionsContent[eTIndex];
			}
		});

		eSourceContent = "";
		$.each(sourceSectionsIndex, function(eSIndex, eSValue){
			if(eSValue == sourceIndexOfSectionsToTransclude[value] ){
				eSourceContent = sourceSectionsContent[eSIndex];
			}
		});

		targetTemp = $.trim(eTargetContent) + "\n{{#transcludeid: " + sourceArticleName + "|" + indexesOfNewTransclusions[value] + "}}";

		//Target article
		$.ajaxq("targetsqueue", {
		    url: urlApi,

		    data:{
			action:'edit',

			title:targetArticleName,

			section:targetIndexOfSectionsToTransclude[value],

			text:targetTemp,

			token:eToken
		    },

		    type:'post',

		    cache:'false',

		    success: function(data){
			    $("#" + indexesOfNewTransclusions[value]).append(" [Target updated] ");
		    }
		});

		// Database
		$.ajaxq("dbqueue",{
			url: "include/php/registerTransclusionInDB.php",

		    data:{
			trid:indexesOfNewTransclusions[value],

			source:sourceArticleName,

			target:targetArticleName,

			sectionId:sourceIndexOfSectionsToTransclude[value],

			trtext:""
		    },

		    type:'post',

		    cache:'false',

		    success: function(data){
				$("#" + indexesOfNewTransclusions[value]).append(" [DB updated] ");
		    }
		});

		nroIguales = 2 * levelOfSourceSections[value];
		indiceTitulo = 0;

		while(nroIguales > 0){
			if( eSourceContent.charAt(indiceTitulo) == '=' ){
				nroIguales--;
			}
			indiceTitulo++;
		}

		sourceTemp = eSourceContent.substr( 0 , indiceTitulo ) + "\n<transclusionid-" + indexesOfNewTransclusions[value] + "> " +  $.trim(eSourceContent.substr(indiceTitulo)) + "\n</transclusionid-" + indexesOfNewTransclusions[value] + ">";
		$.ajaxq("sourcesqueue", {
		    url: urlApi,

		    data:{
			action:'edit',

			title:sourceArticleName,

			section:sourceIndexOfSectionsToTransclude[value],

			text:sourceTemp,

			token:eToken
		    },

		    type:'post',

		    cache:'false',

		    success: function(data){
				$("#" + indexesOfNewTransclusions[value]).append(" [Source updated] ");
		    }
		});

	});
    }
  });
}

function getRandomNumber(lowerBound,upperBound){
	aleatorio = Math.floor(Math.random() * (upperBound - lowerBound)) + lowerBound;
	return aleatorio;
}

function getRandomChar() {
	var numberChars = "0123456789";
	var lowerChars = "abcdefghijklmnopqrstuvwxyz";
	//var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	var charSet = "";

	charSet += numberChars;
	charSet += lowerChars;
	//charSet += upperChars;

	caracter = charSet.charAt(getRandomNumber(0, charSet.length));

	return caracter;
}

function getNewTrid(){
	var newTrid = "";

	var i = 5;

	while( i > 0 ){
		newTrid = newTrid + getRandomChar();
		i--;
	}

	return newTrid;
}